<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    class Graph {
      constructor() {
        this.vertices = new Set();
        this.edges = new Map();
      }

      addVertex(vertex) {
        if (!this.vertices.has(vertex)) {
          this.vertices.add(vertex);
          this.edges.set(vertex, new Set());
        }
      }

      addEdge(startVertex, endVertex) {
        if (!this.vertices.has(startVertex)) {
          this.addVertex(startVertex);
        }
        if (!this.vertices.has(endVertex)) {
          this.addVertex(endVertex);
        }
        this.edges.get(startVertex).add(endVertex);
        this.edges.get(endVertex).add(startVertex);
      }

      bfs(startVertex) {
        let visited = new Set();
        let queue = [startVertex];
        visited.add(startVertex);
        while (queue.length > 0) {
          let currentVertex = queue.shift();
          console.log(currentVertex);
          for (let neighbor of this.edges.get(currentVertex)) {
            if (!visited.has(neighbor)) {
              visited.add(neighbor);
              queue.push(neighbor);
            }
          }
        }
      }

      dfs(startVertex, visited = new Set()) {
        console.log(startVertex);
        visited.add(startVertex);
        for (let neighbor of this.edges.get(startVertex)) {
          if (!visited.has(neighbor)) {
            this.dfs(neighbor, visited);
          }
        }
      }
    }

    let graph = new Graph();
    graph.addEdge('A', 'B');
    graph.addEdge('A', 'C');
    graph.addEdge('B', 'D');
    graph.addEdge('C', 'E');
    graph.bfs('A'); // 输出A B C D E
    graph.dfs('A'); // 输出A B D C E

  </script>
</body>

</html>